<?php


namespace App\Http\Controllers\Api;


use App\Http\Controllers\Controller;
use App\Models\CommodityOrder;
use App\Models\CommodityOrderAssign;
use App\Models\GoodsClass;
use App\Models\Information;
use App\Models\Staff;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Overtrue\EasySms\EasySms;


class ServiceController extends Controller
{
    public function index(Request $request)
    {
        $lng = $request->input('lng');
        $lat = $request->input('lat');

        $staff = Staff::where('is_head', 1)->where('id_number', '<>', '')->where('is_idcar', 1)
            ->select('id', 'head', 'surname', 'work_type', 'account', 'staff_lng', 'staff_lat', 'is_enterprise')
            ->get();
        foreach ($staff as &$v) {
            $v->phone = substr_replace($v->account, '****', 3, 4);
            $v->distance = $this->getDistance($lng, $lat, $v->staff_lng, $v->staff_lat);
        }
        return makeResponse($staff, '提交成功', 200);
    }

    public function goodsClass()
    {
        $class = GoodsClass::orderBy('sort')->get();
        $newClass = $this->getTree($class, 0);
        return makeResponse($newClass, '提交成功', 200);
    }

    public function createOrder(Request $request)
    {
        $user = $request->user();
        $userId = $user['id'];
        $chaoge = '18628035513';


        $data = [
            'internal_order_sn' => self::createSn(),
            'customer_id' => $userId,
            'order_status' => 2,
            'remarks' => $request->input('remarks'),//备注
            'remark_img' => json_encode($request->input('remark_img')),//备注图
            'contacts' => $request->input('contacts'),//联系人
            'mobile' => $request->input('mobile'),//联系电话
            'full_address' => $request->input('full_address'),//服务地址
            'lng_address' => $request->input('lng'),//jing
            'lat_address' => $request->input('lat'),//wei
            'class_id' => $request->input('class_id'),//项目ID
            'class_name' => $request->input('class_name'),//项目名称
        ];
        try {
            $order = CommodityOrder::createOne($data);
            $order->save();
            //短信通知超哥
            $smsConfig = config('sms');
            $sms = new EasySms($smsConfig);
            $data = [
                'template' => 'SMS_175240424',
                'data' => [
                    'code' => 8888
                ]
            ];
            $sms->send($chaoge, $data);
            return makeResponse(['order_id' => $order->id], '提交成功', 200);
        } catch (\Exception $exception) {
            return $this->makeResponse([], $exception->getMessage() . ' [LINE]:' . $exception->getLine(), 500);
        }
    }

    public function orderHeartbeat(Request $request)
    {
        $orderId = $request->input('order_id');
        $order = CommodityOrder::with('staff.staffInfo')->where('id', $orderId)->first();

        if ($order->staff) {
            $order->distance = $this->getDistance($order->lat_address, $order->lng_address, $order->staff->lat, $order->staff->lng);
        } else {
            $order->distance = 0;
        }

        return makeResponse($order, '查询成功', 200);
    }

    public function cancelOrder(Request $request)
    {
        $orderId = $request->input('order_id');
        $order = CommodityOrder::with('staff')->where('id', $orderId)->first();
        CommodityOrder::where('id', $orderId)->update(['order_status' => 5]);
        if ($order->staff && $order->is_assign == 1) {
            information::createOne([
                'title' => '通知消息',
                'content' => '您好，用户取消订单。',
                'staff_id' => $order->staff->staff_id])->save();
        }
        return makeResponse([], '取消成功', 200);
    }

    public function orderList(Request $request)
    {
        $status = $request->input('status');//2-未完成/已接单(待服务);4-已完成/已确认(已服务);5,已关闭已取消
        $user = $request->user();
        $userId = $user['id'];

        if ($status == 2) {

            $order = CommodityOrder::with('staff.staffInfo')->where('customer_id', $userId)->whereIn('order_status', [2, 3])
                ->orderBy('created_at', 'desc')
                ->paginate(10);
        } else {

            $order = CommodityOrder::with('staff.staffInfo')->where('customer_id', $userId)->where('order_status', $status)
                ->orderBy('created_at', 'desc')
                ->paginate(10);
        }

        foreach ($order as &$v) {
            if ($v->remark_img) {
                $v->remark_img = json_decode($v->remark_img);
            } else {
                $v->remark_img = [];
            }
        }
        return makeResponse($order, '查询成功', 200);
    }

    public function changeStaff(Request $request)
    {
        $orderId = $request->input('order_id');
        $staffId = $request->input('staff_id');


        CommodityOrder::where('id', $orderId)->update(
            ['is_assign' => 0,
                'created_at' => date('Y-m-d H:i:s'),
                'order_status' => 2]
        );

        CommodityOrderAssign::destroy($staffId);

        return makeResponse([], '成功', 200);
    }

    public function confirmOrder(Request $request)
    {
        $orderId = $request->input('order_id');
        CommodityOrder::where('id', $orderId)->update(['order_status' => 4, 'finished_at' => date("Y-m-d H:i:s")]);
        return makeResponse([], '确认成功', 200);
    }
}